package com.java.util;

import java.util.ArrayList;
import java.util.List;

import java.util.concurrent.TimeUnit;

interface Solver {
    boolean solve();
}

class Queen {
    private int row;
    private int col;

    public Queen(int row, int col) {
        this.row = row;
        this.col = col;
    }

    public int getRow() {
        return row;
    }

    public int getCol() {
        return col;
    }
}

class ChessBoard implements Solver {
    private final int size;
    private final List<Queen> queens;

    public ChessBoard(int size) {
        this.size = size;
        this.queens = new ArrayList<>();
    }

    public void placeQueen(Queen queen) {
        queens.add(queen);
    }

    public boolean isSafe(int row, int col) {
        for (Queen q : queens) {
            if (q.getRow() == row || q.getCol() == col ||
                    Math.abs(q.getRow() - row) == Math.abs(q.getCol() - col)) {
                return false;
            }
        }
        return true;
    }
    // 1837 919

    public void printBoard() {
        char[][] board = new char[size][size];
        for (char[] row : board) {
            java.util.Arrays.fill(row, '.');
        }
        for (Queen q : queens) {
            board[q.getRow()][q.getCol()] = 'Q';
        }
        for (char[] row : board) {
            System.out.println(new String(row));
        }
    }

    public boolean solve(int row) {
        if (row == size) {
            return true;
        }
        for (int col = 0; col < size; col++) {
            if (isSafe(row, col)) {
                placeQueen(new Queen(row, col));
                if (solve(row + 1)) {
                    return true;
                }
                // 回溯
                queens.remove(queens.size() - 1);
            }
        }
        return false;
    }

    @Override
    public boolean solve() {
        return solve(0);
    }
}

public class EightQueensExample {
    public static void main(String[] args) {
        ChessBoard chessBoard = new ChessBoard(8);
        if (chessBoard.solve()) {
            chessBoard.printBoard();
        } else {
            System.out.println("No solution found.");
        }
    }
}
